package cn.hywx.convert.beans;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.hywx.convert.utils.DbcpDataSource;

public class DocumentBean {
	
	/*
	 * document convert state
	 */
	public static String STATE_CONVERTED = "2";
	public static String STATE_UNCONVERTED = "1";
	
	/**
	 * document table field 
	 */
	String id;
	String name;
	String flag;
	
	
	/**
	 * change document state when document convert sucess
	 * @param id
	 * @param flag document convert flag
	 * @return
	 */
	public static boolean changeState(String id,String flag){
		DataSource ds = DbcpDataSource.getInstance().getDataSource();
		QueryRunner rn = new QueryRunner(ds);
		int affected = 0;
		try {
			affected = rn.update("update document set flag=? where id=?", new Object[]{flag,id});
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return affected>0;
	}
	
	
	/**
	 * get unconverted document queue list
	 * @return List<DocumentBean>
	 */
	public static List<DocumentBean> getDocConvertQueue(){
		DataSource ds = DbcpDataSource.getInstance().getDataSource();
		BeanListHandler<DocumentBean> blh = new BeanListHandler<DocumentBean>(DocumentBean.class);
		QueryRunner qr = new QueryRunner(ds);
		String sql = "select * from document where flag = ?";
		List<DocumentBean> ldb = null;
		try {
			ldb = qr.query(sql, blh,DocumentBean.STATE_UNCONVERTED);
		} catch (SQLException e) {
			System.out.println(sql+":\n"+e.getMessage());
		}
		return ldb;
	}
	
	
	public static void main(String [] args){
		DocumentBean.changeState("2", DocumentBean.STATE_UNCONVERTED);
		List<DocumentBean> ldb = DocumentBean.getDocConvertQueue();
		System.out.println(ldb);
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	@Override
	public String toString() {
		return "DocumentBean [id=" + id + ", name=" + name + ", flag=" + flag
				+ "]";
	}
	
}
